package com.example.mykotlin.base.interceptor

import jakarta.servlet.ReadListener
import jakarta.servlet.ServletInputStream
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletRequestWrapper
import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.IOException
import java.io.InputStreamReader
import java.nio.charset.Charset


class JsonRequestWrapper(request: HttpServletRequest) : HttpServletRequestWrapper(request) {

    private val body: ByteArray

    init {
        body = readBytes(request.reader)
    }

    private fun readBytes(bufferedReader: BufferedReader, charset: Charset = Charsets.UTF_8): ByteArray {
        val sb = StringBuffer()
        var s: String?
        while ((bufferedReader.readLine().also { s = it }) != null) {
            sb.append(s);
        }
        if (sb.isEmpty()) {
            return "".toByteArray(charset)
        }
        return sb.toString().toByteArray(charset)
    }

    fun getBodyString() = String(body)

    @Throws(IOException::class)
    override fun getReader() = BufferedReader(InputStreamReader(inputStream))

    @Throws(IOException::class)
    override fun getInputStream(): ServletInputStream {
        val bis = ByteArrayInputStream(body)
        return object : ServletInputStream() {
            @Throws(IOException::class)
            override fun read(): Int {
                return bis.read()
            }

            override fun isFinished(): Boolean {
                return false
            }

            override fun isReady(): Boolean {
                return false
            }

            override fun setReadListener(readListener: ReadListener) {}
        }
    }
}